package com.egg.common.spring.filter;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.egg.common.spring.annotation.SensitiveAnnotation;
import com.egg.common.spring.enums.sensitive.SensitiveStrategyEnum;
import com.egg.common.spring.service.SensitiveService;
import com.egg.common.spring.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

@Slf4j
public class SensitiveFilter implements ValueFilter {
 
 
    @Override
    public Object process(Object object, String name, Object value) {
        if (ObjectUtil.isEmpty(value) || !(value instanceof String) ) {
            return value;
        }
        SensitiveService sensitiveService = null;
        try {
            sensitiveService = SpringContextUtil.getBean(SensitiveService.class);
        } catch (Exception e) {

        }
        if (null != sensitiveService && !sensitiveService.isSensitive()) {
            return value;
        }
        try {
            Field field = object.getClass().getDeclaredField(name);
            SensitiveAnnotation sensitive;
            if (String.class != field.getType() || (sensitive = field.getAnnotation(SensitiveAnnotation.class)) == null) {
                return value;
            }
            String valueStr = (String) value;
            SensitiveStrategyEnum strategy = sensitive.strategy();
            return strategy.desensitizer().apply(valueStr);

        } catch (Exception e) {
            log.error("脱敏数据 类型 : {} 值 : {},异常信息 : {}", object.getClass(), value);
            return value;
        }
    }


}